//
//  NetHandleBlock.m
//  HYHOME
//
//  Created by dllo on 16/2/26.
//  Copyright © 2016年 Mac. All rights reserved.
//

#import "NetHandleBlock.h"

@implementation NetHandleBlock
+ (void)networkingWithURL:(NSString *)string completeHandel:(void (^)(NSURLResponse *, NSData *, id))block{
    
    // 字符串转码
    NSString *codeStr = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:codeStr];
    
    // session
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 回到主线程(GCD).
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 如果有数据, 再执行
            if (data) {
                
                // 数据解析
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                
                // 调用 block
                block(response, data, result);
                
            }
            
        });
        
    }];
    
    [dataTask resume];
}

@end
